package com.example.addrparserdemo.controller;

import com.example.addrparserdemo.service.LocationParserEngineService;
import com.example.addrparserdemo.vo.LocationVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.spiro.addrparser.common.RegionInfo;
import tech.spiro.addrparser.parser.Location;
import tech.spiro.addrparser.parser.LocationParserEngine;

import java.util.Objects;

/**
 * 地址 Controller
 *
 * @author leiguoqing
 */
@Slf4j
@RestController
@RequestMapping("/")
public class LocationController {

    @Autowired
    private LocationParserEngineService locationParserEngineService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 根据经纬度获取位置信息（省市区）
     *
     * @param lon 经度
     * @param lat 纬度
     * @return 位置信息（省市区）
     */
    @GetMapping("/location")
    public String getLocation(Double lon, Double lat) throws JsonProcessingException {
        // 获取位置解析引擎
        final LocationParserEngine engine = locationParserEngineService.getEngine();

        if (Objects.isNull(engine)) {
            log.error("获取位置解析引擎为空");
            return "engine is null";
        }

        StopWatch sw = new StopWatch("根据经纬度获取位置信息（省市区）");
        sw.start("parse location");

        // 执行解析操作
        // 深圳-信利康大厦：113.888526,22.501119
        // 香港：114.209324,22.257168
        // 台湾：120.873733,23.393628
        // 澳门：113.565593,22.11745
        Location location = engine.parse(lon, lat);
        if (Objects.isNull(location)) {
            log.warn("location is null");
            return "location is null";
        }

        /* 获取省市区信息 */

        // 省信息
        RegionInfo provInfo = location.getProv();
        // 省名称
        final String provName = provInfo.getName();
        log.info("provName is {}", provName);


        // 市信息
        RegionInfo cityInfo = location.getCity();
        // 市名称
        final String cityName = cityInfo.getName();
        log.info("cityName is {}", cityName);

        // 区信息
        RegionInfo districtInfo = location.getDistrict();
        // 区名称
        final String districtName = districtInfo.getName();
        log.info("districtName is {}", districtName);

        // 包装返回值
        final LocationVO locationVO = LocationVO.builder()
                .province(provName)
                .city(cityName)
                .district(districtName)
                .build();

        sw.stop();
        log.info(sw.prettyPrint());

        return objectMapper.writeValueAsString(locationVO);
    }

}
